﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;
using Diploma.Models;
using Diploma.Validation;
using DiplomaWeb.Configuration;
using DiplomaWeb.Models.Account;

namespace DiplomaWeb.Controllers
{
    public class MasterController : Controller
    {
        private readonly DataManager dataManager;

        protected IEnumerable<ValidationError> ValidationErrors = new List<ValidationError>();
        private User loggedUser;
        private static DiplomaConfiguration configuration;
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        public MasterController(DataManager dataManager)
        {
            this.dataManager = dataManager;
        }

        protected DataManager DataManager
        {
            get { return dataManager; }
        }

        protected DiplomaConfiguration Configuration
        {
            get
            {
                if(configuration == null)
                    configuration = new DiplomaConfiguration();
                return configuration;
            }
        }

        protected string UserEmail
        {
            get { return System.Web.HttpContext.Current.User.Identity.Name; }
        }

        protected User LoggedUser
        {
            get
            {
                if (loggedUser == null)
                    loggedUser = dataManager.UsersRepository.GetUserByEmail(UserEmail, false);

                return loggedUser;
            }
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null)
            {
                MembershipService = new AccountMembershipService();
            }

            base.Initialize(requestContext);
        }
        
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["LoggedUser"] = LoggedUser;
        }

        protected string RenderPartialViewToString()
        {
            return RenderPartialViewToString(null, null);
        }

        protected string RenderPartialViewToString(string viewName)
        {
            return RenderPartialViewToString(viewName, null);
        }

        protected string RenderPartialViewToString(object model)
        {
            return RenderPartialViewToString(null, model);
        }

        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

        protected void LoggerInfo(string message)
        {
            DataManager.LoggerRepository.AddInfo(new DiplomaError
            {
                ErrorID = Guid.NewGuid(),
                ErrorMessage = message,
                ErrorType = null,
                UserName = UserEmail,
                Occured = DateTime.Now,
                IP = Request.UserHostAddress,
                Browser = Request.Browser.Browser,
                Level = String.Empty,
            });
        }

        protected void SignUpInSystem(string email)
        {
            DataManager.LoggerRepository.AddLoginEvent(new DiplomaError
            {
                ErrorID = Guid.NewGuid(),
                ErrorMessage = "User entered in the system.",
                ErrorType = null,
                UserName = email,
                Occured = DateTime.Now,
                IP = Request.UserHostAddress,
                Browser = Request.Browser.Browser,
                Level = String.Empty
            });
        }
    }
}